package com.dyoud.api.sms.controller;

import javax.annotation.Resource;

import org.douyoudian.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dyoud.api.ReturnInfo;
import com.dyoud.api.user.service.UserApiService;
import com.dyoud.core.ResponseBean;
import com.dyoud.core.code.RedisSmsManager;
import com.dyoud.core.enums.SmsTypeEnum;
import com.dyoud.user.api.model.User;

/**
 * 发送短信
 * 
 * @author Jonathan
 * @date 2018/03/01
 *
 */
@RestController
@RequestMapping("sms")
public class SmsController {

    @Resource
    private RedisSmsManager smsManager;

    @Resource
    private UserApiService userApiService;

    @Value("${is_dev}")
    private boolean isDev;

    /**
     * 发送短信验证码
     * 
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.GET)
    public ResponseBean send(String phone, Integer type) {

        SmsTypeEnum smsType = SmsTypeEnum.getSmsType(type);
        if (smsType == SmsTypeEnum.REG /*|| smsType == SmsTypeEnum.LOGIN*/) {
            User user = userApiService.getByPhone(phone);
            if (user != null) {
                return new ResponseBean().fail("用户已存在");
            }

        }
        String code = RandomUtils.randomSmsCode();
        boolean isOk = smsManager.sendCode(phone, "【都有店】您的验证码是#code#。如非本人操作，请忽略本短信".replace("#code#", code), smsType);
        if (!isOk) {
            return new ResponseBean().fail(ReturnInfo.SEND_SMS_CODE, ReturnInfo.SEND_SMS_CODE_MSG);
        }
        return new ResponseBean().success(code);
    }

    /**
     * 检查短信验证码
     * 
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping(value = "/checkSmsCode", method = RequestMethod.GET)
    public ResponseBean checkSmsCode(@RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "code", required = true) String code,
            @RequestParam(value = "type", required = true) Integer type) {
        boolean isOk = smsManager.checkCode(phone, code, SmsTypeEnum.getSmsType(type));
        if (!isDev) {
            if (!isOk) {
                return new ResponseBean().fail(ReturnInfo.SMS_INVALID_CODE, ReturnInfo.SMS_INVALID_MSG);
            }
        }
        return new ResponseBean().success(true);
    }

}
